package fr.lille.inria.adam.lifl.EcoGardeInventory.Tasks;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.Constantes;

public class RetrieveCommunesTask extends
		HttpAsyncTask<Void, Map<String, String>> {

	private static final String TAG = "RetrieveCommunesTask";

	@Override
	protected Map<String, String> doInBackground(Void... params) {
		Log.d(TAG, "start refresh cats");
		Map<String, String> result = new HashMap<String, String>();
		System.out.println("deb retrieve");
		HttpGet allRequest = new HttpGet(Constantes.HTTP_FIRST_GROUP); // Je récupère la page de recherche
		try {
			// Et j'extrais les catgories et leurs identifiants depuis la liste
			// droulante
			HttpResponse catResult = browser.execute(allRequest);
			String rawResponse = super.getStringContent(catResult);
			Log.v("RetrieveCommunesTask.rawResponse", rawResponse);
			Document doc = Jsoup.parse(rawResponse);
			
			String[] debug = rawResponse.split("select");
			for (String s : debug) {
				Log.d(TAG, "String[] debug  " + s);
			}
			Element sel = doc.select("select#listeCommune").first().parent()
					.parent();
			Log.d(TAG, "Element sel   " + sel.text());
			Elements options = doc.select("select#listeCommune>option");
			for (Element option : options) {
				if (option.attr("value").equals(""))
					continue;
				Log.d(TAG, "value = " + option.text());
				result.put(option.text(), option.attr("value"));
			}
			Log.d(TAG,
					String.format("done refresh cats (%d results)",
							result.size()));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
